extends Node

@onready var main_menu = $MainMenu
@onready var enter: Control = $MainMenu/Enter


# Called when the node enters the scene tree for the first time.
func _ready():
	# 载入游戏设置
	load_game()
	# 将按钮绑定到开始游戏
	enter.startgame.connect(start_to_game)
	# 将菜单中的保存与游戏设置保存绑定
	enter.key_strock_changed.connect(save_setting)
	pass # Replace with function body.


func load_scene():
	var playworld = preload("res://World/world.tscn").instantiate()
	get_tree().root.add_child(playworld)
	playworld.Menu.quit.connect(back_to_main_menu)

func back_to_main_menu():
	enter.show()


func start_to_game() -> void:
	load_scene()


func save_setting() -> void:
	save_game()


## 保存游戏
func save_game():
	var save_file = FileAccess.open("user://save_setting.save", FileAccess.WRITE)
	var save_nodes = get_tree().get_nodes_in_group("Setting")
	# print(save_nodes)
	for node in save_nodes:
		# Now, we can call our save function on each node.
		var node_data = node.call("save_data")
		var json_string = JSON.stringify(node_data)
		save_file.store_line(json_string)
	# print("保存成功")
	load_game()
	
## 载入游戏
func load_game():
	if not FileAccess.file_exists("user://save_setting.save"):
		return # Error! We don't have a save to load.
	var save_file = FileAccess.open("user://save_setting.save", FileAccess.READ)
	while save_file.get_position() < save_file.get_length():
		var json_string = save_file.get_line()

		# Creates the helper class to interact with JSON
		var json = JSON.new()

		# Check if there is any error while parsing the JSON string, skip in case of failure
		var parse_result = json.parse(json_string)
		if not parse_result == OK:
			print("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())
			continue

		# Get the data from the JSON object
		var node_data = json.get_data()
		# print(node_data)
		
		for i in get_tree().get_nodes_in_group("Setting"):
			if i.call("get_save_name") == node_data["node"]:
				i.call("load_data",node_data)
				# print("载入成功")
		# print("载入完成")
